/**
 * Created with IntelliJ IDEA
 * Description:
 * User: SEKI TOMOKI
 * Date: 2023-09-27
 * Time: 14:20
 */
class Solution {
    public int pivotIndex(int[] nums) {
        /*
        if(nums.length == 1) {
            return 0;
        }

        int sumOfLeft = 0;
        for(int i = 0; i < nums.length; i++) {
            if(i > 0) {
                 sumOfLeft += nums[i- 1];
            }
            int sumOfRight = 0;
            for(int j = i + 1; j < nums.length; j++) {
                 sumOfRight += nums[j];
            }

            if(sumOfLeft == sumOfRight) {
                return i;
            }
        }

        return -1;
        */

        //改进
        if(nums.length == 1) {
            return 0;
        }
        int sumOfLeft = 0;
        int sumOfRight = 0;

        int i = 0;
        for(i = 1; i < nums.length; i++) {
            sumOfRight  += nums[i];
        }

        i = 0;
        while(sumOfLeft != sumOfRight && i < nums.length - 1){
            i++;
            sumOfLeft += nums[i - 1];
            sumOfRight -= nums[i];
        }

        if(sumOfLeft == sumOfRight) {
            return i;
        }else {
            return -1;
        }
    }
}
